import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Spin, message, Card, Form, Radio, Popconfirm, Modal, Icon, DatePicker, Select, Row, Col, Input, AutoComplete } from 'antd';
import InvItemList from '../InvItemList';
import styles from './styles.less';
import moment from 'moment';
import AccountJS from '@/utils/account';

const FormItem = Form.Item;
const { Option: AutoCompleteOption } = AutoComplete;

@connect(({ user, relationer, mbl, port }) => ({
  relationers: relationer.list,
  ports: port.list,
  mbl: mbl.current,
  cUser: user.currentUser,
}))
@Form.create()
class Comp extends PureComponent {

  state = {
    visible: false,
    list: [],
    current: undefined,
    selectedRelationer: null,

    invItemCount: 0,
  };

  componentDidMount() {
    const { inv } = this.props;
    this.setCurrent(inv);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.inv !== this.props.inv) {
      this.setCurrent(nextProps.inv);
    }
  }

  setCurrent(inv) {
    const { relationers } = this.props;
    if (inv) {
      this.setState({
        current: inv,
        relationer: relationers.find(r => r.id === inv.relationerId)
      });
    }
  }

  handleRelationerChanged(value) {
    const { relationers } = this.props;
    if (value) {
      this.setState({ selectedRelationer: relationers.find(r => r.id === Number(value)) });
    }
  }

  handleSubmit(e) {
    e.preventDefault();
    let { current: vm } = this.state;
    const { selectedRelationer } = this.state;

    var isValid = true;

    // Header FORM
    this.props.form.validateFields((err, values) => {
      if (err) {
        isValid = false;
        return;
      }

      vm = {
        ...vm,
        ...values,
        relationerId: selectedRelationer ? selectedRelationer.id : vm.relationerId > 0 ? vm.relationerId : 0,
        // relationerId: selectedRelationer ? selectedRelationer.id : 0,
        relationerName: selectedRelationer ? selectedRelationer.objectName : values.relationerName,
      };
    });

    console.log("VM in header:", vm);

    //  Inv Item  FORM
    const { form: listForm } = this.invItemListForm.props;
    listForm.validateFields((err, values) => {

      console.log("VALUES FROM inv list", values);
      if (err) {
        isValid = false;
        return;
      }
      vm = {
        ...vm,
        items: values,
      }
    });

    if (!isValid)
      return;

    console.log("VM", vm);

    this.props.onSave(vm);
  }

  render() {
    const { cUser, loading, form: { getFieldDecorator }, rec } = this.props;
    const { relationers } = this.props;
    const { current, shipper } = this.state;

    const noLabelFormLayout = {
      labelCol: {
        sm: { span: 0 },
      },
      wrapperCol: {
        sm: { span: 24 },
      },
    };

    // const invTypeName = (type) => ['工厂账单', '客户帐单', '供应商账单'][type - 1];

    const recInfo = () => (<span>
      {rec.map(r => <span style={{ marginLeft: '1em', color: r.receive && r.receive >= r.amount ? 'black' : 'red' }} >
        {AccountJS.formatMoney(r.amount, r.currencyName)}
      </span>)}
    </span>);


    const headerEditor = () => {
      return (<Form>
        <Row className={styles.sft} style={{ height: '3em' }} >
          <Col span={2} className={styles.leaderCol} style={{ lineHeight: '3em' }} >单位名称</Col>
          <Col span={10} style={{ paddingLeft: '6px', display: 'flex', lineHeight: '3em' }}>
            <FormItem label="" {...noLabelFormLayout} style={{ minWidth: '80%' }}>
              {getFieldDecorator('relationerName', {
                initialValue: shipper ? shipper.objectName : current && current.relationerName,
              })(
                <AutoComplete
                  placeholder="名称"
                  autoFocus={true}
                  backfill={true}
                  onChange={(value) => this.handleRelationerChanged(value)}
                  filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1} >
                  {relationers.map((rel) => { return <AutoCompleteOption key={rel.id} value={String(rel.id)} >{rel.objectName}</AutoCompleteOption> })}
                </AutoComplete>
              )}
            </FormItem>
            <span style={{ marginLeft: '1em' }}>{current && '(' + ['工厂账单', '客户帐单', '供应商账单'][current.invoiceType - 1] + ')'}</span>
          </Col>
          <Col span={4} offset={8}>
            <div style={{ display: 'flex', float: "right", height: '100%', marginTop: '1em', marginRight: '.5em' }}>
              {this.props.actions}
              <a style={{ marginLeft: '8px', display: current && current.isLock === 1 ? 'none' : '' }} onClick={(e) => this.handleSubmit(e)} > 保存</a>
            </div>
          </Col>
        </Row>
      </Form>
      );
    };

    return (
      <div className={styles.border}>
        <Spin spinning={loading}  >
          <div className={styles.container}>
            {headerEditor()}
            <div className={styles.boxList}>
              <InvItemList inv={current} getInstance={form => (this.invItemListForm = form)} />
            </div>
            <div style={{ padding: '6px', lineHeight: '2.2em' }}>
              <div style={{ float: 'right' }}>合计:{recInfo()}</div>
              <div>发票:{current && current.faPiaoState}</div>
              <div>提单:{current && current.tiDanState}</div>
            </div>
          </div>
        </Spin>
      </div>
    );
  }
}

export default Comp;
